<?php

namespace app\api\controller;

use app\admin\model\dts\activity\Notes;
use app\admin\model\dts\todo\Items;
use think\Db;
use think\Log;
use think\Collection;
/**
 * 通用接口
 */
class Service
{
    //通知信息
    public function gardenNotice($data, $istc, $type, $title, $page = 1, $pagesize = 10) {

        $query1 = $title ? ['dgn.title' => ['LIKE', '%'.$title.'%']] : [];
        $query2 = $type ? ['dgn.admin_id' => $data['id']] : [];
        
        $query3 = '1=1';
        if($type == 0) {
            if($istc == 0) {
                $query3 = 'FIND_IN_SET('.$data['id'].',dgn.parent_notice_range) > 0';
            }else {
                $query3 = 'FIND_IN_SET('.$data['id'].',dgn.teacher_notice_range) > 0';
            }
        }

        $list = Db::name('dts_garden_notice')->alias('dgn')
        ->field('dgn.id,dgn.type,dgn.title,dgn.content,dgn.push_text,dgn.teacher_read_range,dgn.parent_read_range,ad.nickname,FROM_UNIXTIME(dgn.createtime,"%Y-%m-%d %H:%i") as createtime')
        ->join('admin ad', 'ad.id = dgn.admin_id', 'left')
        ->where(array_merge($query1, $query2))
        ->whereRaw($query3)
        ->order('dgn.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        return $list;
    }

    //通知信息详情
    public function gardenNoticeInfo($data, $istc, $id) {
        
        $info = Db::name('dts_garden_notice')->alias('dgn')
        ->field('dgn.*,FROM_UNIXTIME(dgn.createtime,"%Y-%m-%d %H:%i") as createtime,ad.nickname')
        ->join('admin ad', 'ad.id = dgn.admin_id', 'left')
        ->where('dgn.id', $id)
        ->find();

        if(!$info) {
            ajaxerror('查询参数有误');
        }

        if($istc == 0) {
            $arr = $info['parent_read_range'] ? array_unique(explode(',', $info['parent_read_range'])) : [];
            array_push($arr, $data['id']);
            $update = ['parent_read_range' => join(',', $arr)];
        }else {
            $arr = $info['teacher_read_range'] ? array_unique(explode(',', $info['teacher_read_range'])) : [];
            array_push($arr, $data['id']);
            $update = ['teacher_read_range' => join(',', $arr)];
        }

        Db::name('dts_garden_notice')->where('id', $id)->update($update);

        return $info;
    }

    /**
     * 班级活动
     * $data = user admin
     * $istc = 0家长端 1教师端
     * $isAuth 是否有权限
     * $gradeId 查询年级Id
     * $classesId 教师端传的班级Id
     */
    public function classesActivity($data, $istc, $isAuth, $gradeId, $classesId, $starttime, $endtime, $page = 1, $pagesize = 10) {
        $query2 = []; $query3 = [];
        if($istc == 0) {
            $classesIds = array_column($data['student'], 'classes_id');
            $query1 = ['dca.classes_id' => ['in', $classesIds]];
        }else {
            if($isAuth) {
                $query1 = $classesId ? ['dca.classes_id' => $classesId]: [];
                $query2 = $gradeId ? ['dc.grade_id' => $gradeId] : [];
                $query3 = $starttime && $endtime ? ['dca.createtime' => ['between', [strtotime($starttime), strtotime($endtime)]]] : [];
            }else {
                $query1 = ['dca.classes_id' => $classesId];
            }
        }

        $list = Db::name('dts_classes_activity')->alias('dca')
        ->field('dca.id,dca.title,dca.describes,dca.images,dca.createby,FROM_UNIXTIME(dca.createtime,"%Y-%m-%d %H:%i") as createtime,dc.name as classname')
        ->join([
            ['dts_classes dc', 'dc.id = dca.classes_id', 'left']
        ])
        ->where(array_merge($query1, $query2, $query3))
        ->order('dca.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        return $list;
    }

    /**
     * 活动小记
     * $type 0全部 1=我发布 2=家长发布
     */
    public function activityNotes($data, $istc, $type, $isAuth, $gradeId, $classesId, $realmId, $labelId, $page = 1, $pagesize = 10) {
        
        $query2 = []; $query3 = []; $query4 = []; $query7 = []; $query8 = [];

        if(!$istc) {
            $query1 = ['dan.classes_id' => $data['classes_id'], 'dan.category' => Notes::category_2];
            if($type == 1) {
                $query7 = ['dan.user_id' => $data['id']];
            }
        }else {
            $query1 = ['dan.category' => Notes::category_1];
            if($isAuth) {
                $query2 = $classesId ? ['dan.classes_id' => $classesId] : [];
            }else {
                $query2 = ['dan.classes_id' => $classesId];
            }
            $query2 = $gradeId ? ['dc.grade_id' => $gradeId] : [];
        }
        
        $query5 = $realmId ? ['dan.dts_activity_realm_id' => $realmId] : [];
        $query6 = $labelId ? ['dan.dts_activity_label_id' => $labelId] : [];

        $list = Db::name('dts_activity_notes')->alias('dan')
        ->field('dan.id,us.avatar,us.username,dar.name as darname,dal.name as dalname,dan.observe_goal,ad.nickname,FROM_UNIXTIME(dan.createtime,"%Y-%m-%d %H:%i") as createtime')
        ->join([
            ['admin ad', 'ad.id = dan.admin_id', 'left'],
            ['user us', 'us.id = dan.user_id', 'left'],
            ['dts_classes dc', 'dc.id = dan.classes_id', 'left'],
            ['dts_activity_realm dar', 'dar.id = dan.dts_activity_realm_id', 'left'],
            ['dts_activity_label dal', 'dal.id = dan.dts_activity_label_id', 'left'],
        ])
        ->where(array_merge($query1, $query2, $query3, $query4, $query5, $query6, $query7, $query8))
        ->order('dan.createtime', 'desc')
        ->paginate($pagesize, false, ['page' => $page]);

        return $list;
    }


    //活动小记详情
    public function activityNotesInfo($notesId, $istc) {

        $query1 = ['dan.id' => $notesId];
        $query2 = $istc ? ['dan.category' => 1] : ['dan.category' => 2];

        $info = Db::name('dts_activity_notes')->alias('dan')
        ->field('dan.*,FROM_UNIXTIME(dan.createtime,"%Y-%m-%d %H:%i") as createtime,
        dc.name as classname,GROUP_CONCAT(stu.avatar) as avatars,GROUP_CONCAT(stu.username) as usernames,GROUP_CONCAT(stu.relationship) as relationships,ad.nickname,dar.name as darname,dal.name as dalname')
        ->join([
            ['dts_classes dc', 'dc.id = dan.classes_id', 'left'],
            ['dts_student stu', 'FIND_IN_SET(stu.id,dan.student_ids)', 'left'],
            ['admin ad', 'ad.id = dan.admin_id', 'left'],
            ['dts_activity_realm dar', 'dar.id = dan.dts_activity_realm_id', 'left'],
            ['dts_activity_label dal', 'dal.id = dan.dts_activity_label_id', 'left'],
        ])
        ->where(array_merge($query1, $query2))
        ->find();
        
        if($info) {
            $info['evaluateList'] = Db::name('dts_activity_notes_evaluate')->alias('dane')
            ->field('dane.*,ad.nickname,FROM_UNIXTIME(dane.createtime,"%Y-%m-%d %H:%i") as createtime')
            ->join('admin ad', 'ad.id = dane.admin_id', 'left')
            ->where('dane.dts_activity_notes_id', $notesId)
            ->select();
        }

        return $info;
    }

    
    //行政提交
    public $template1 = 'CVVdBPC7G8N7Ylc-YtTo-Uhi6JM-4euBBHKhSlfHPos';
    //行政审批
    public $template2 = 'CVVdBPC7G8N7Ylc-YtTo-RRqXbx5CqKYj3h913Wb-dU';
    //维修提交
    public $template3 = 'VOl9TpQW13G0JnByoPWr5lugZcDUetzMpk3oYBI17gU';
    //维修完成
    public $template4 = '_q1r6De8qn68B8l2YghGoDr7VpoWyNCxgrRo4EFLoLc';
    //巡检完成
    public $template5 = 'pZ_puHYT3QiT58TFL5to9-3oWE1FertzZE2pLwH47sc';

    protected $map = null;

    public function __construct()
    {
        $this->map = new Collection;

        $this->map['contract'] = 'pages/index/administration/contract/detail';
        $this->map['seal'] = 'pages/index/administration/usingSeal/detail';
        $this->map['askfor'] = 'pages/index/administration/askLeave/detail';
        $this->map['usecar'] = 'pages/index/administration/car/application/detail';
        $this->map['refuel'] = 'pages/index/administration/car/cheerOn/detail';
        $this->map['carep'] = 'pages/index/administration/car/maintenance/detail';
        $this->map['functional'] = 'pages/index/administration/room/detail';
        $this->map['procure'] = 'pages/index/administration/advance/detail';
        $this->map['fault'] = 'pages/index/administration/fault/detail';
        $this->map['patrol'] = 'pages/index/administration/patrol/detail';
        $this->map['point'] = 'pages/index/administration/inspection/detail';
        $this->map['issues'] = 'pages/index/administration/major/detail';
        $this->map['travel'] = 'pages/index/administration/travel/detail';
        $this->map['official'] = 'pages/index/administration/document/detail';
        $this->map['classify'] = 'pages/index/administration/file/detail';
        $this->map['daily'] = 'pages/index/administration/dailySupplies/detail';
        $this->map['food'] = 'pages/index/administration/foodSupplies/detail';
        $this->map['expen'] = 'pages/index/administration/consumable/detail';
        $this->map['repair'] = 'pages/index/maintenance/detail';
        $this->map['meeting'] = 'pages/index/meeting/recordsDetail';
    }

    public function jumpUrl($key) {

        if ($this->map->offsetExists($key)) {
            return $this->map->offsetGet($key);
        }

        return 'pages/index/index';
    }

    //发送公众号消息
    public function wechatmessage($adminId, $templateId, $url, $data) {
        $admin = \app\admin\model\Admin::get($adminId);
        if($admin && $admin['open_id']) {
            try {
                $weChat = new \app\api\library\WeChat;
                $re = $weChat->getApp()->template_message->send([
                    'touser' => $admin['open_id'],
                    'template_id' => $templateId,
                    'url' => 'https://h5.sz-dts.com/#/' . $url,
                    'miniprogram' => [],
                    'data' => $data,
                ]);
                Log::write('wechatmessage--success--'.json_encode($re, JSON_UNESCAPED_UNICODE));
            }catch(\Exception $e){
                Log::write('wechatmessage--error--'.json_encode($re, JSON_UNESCAPED_UNICODE));
            }
        }
    }

    public function wechatmessagebyopenid($openid, $templateId, $url, $data) {
        try {
            $weChat = new \app\api\library\WeChat;
            $re = $weChat->getApp()->template_message->send([
                'touser' => $openid,
                'template_id' => $templateId,
                'url' => 'https://h5.sz-dts.com/#/' . $url,
                'miniprogram' => [],
                'data' => $data,
            ]);
            Log::write('wechatmessage--success--'.json_encode($re, JSON_UNESCAPED_UNICODE));
        }catch(\Exception $e){
            Log::write('wechatmessage--error--'.json_encode($re, JSON_UNESCAPED_UNICODE));
        }
    }


    //待办消息
    public function savetodoitem($title, $category, $adminId, $approveId = 0) {
        $db = \app\admin\model\dts\todo\Items::create(['title' => $title, 'category' => $category, 'approve_id' => $approveId, 'admin_id' => $adminId, 'status' => 0]);
        return $db->getData();
    }

    public function edittodoitem($todoId, $title, $category, $adminId) {
        \app\admin\model\dts\todo\Items::where('id', $todoId)->update(['title' => $title, 'category' => $category, 'admin_id' => $adminId, 'status' => 0]);
    }

    public function handletodoitem($todoIds, $adminId = 0) {
        $query = ['id' => ['in', $todoIds]];
        if($adminId) {
            $query['admin_id'] = $adminId;
        }
        \app\admin\model\dts\todo\Items::where($query)->update(['status' => 1]);
    }

    public function handletodoitembyapprove($approveId, $adminId = 0) {
        $query = ['approve_id' => $approveId];
        if($adminId) {
            $query['admin_id'] = $adminId;
        }
        \app\admin\model\dts\todo\Items::where($query)->update(['status' => 1]);
    }

    //查询特殊人员
    public function specialList($ruleId, $adminId = 0) {
        
        $query = $adminId ? ['admin.id' => $adminId] : [];

        $list = Db::name('admin')->alias('admin')
        ->field('admin.id,admin.nickname,admin.open_id,admin.open_avatar,admin.open_nickname')
        ->join([
            ['auth_group_access access', 'access.uid = admin.id'],
            ['auth_group groups', 'groups.id = access.group_id']
        ])
        ->where($query)
        ->whereRaw('FIND_IN_SET('.$ruleId.', groups.rules) > 0')
        ->select();

        return $list;
    }
}